package com.wjs.gulimall.gulimallproduct.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.utils.R;
import com.wjs.gulimall.gulimallproduct.VO.SecKillInfoVo;
import com.wjs.gulimall.gulimallproduct.VO.SkuItemSalAttrVo;
import com.wjs.gulimall.gulimallproduct.VO.SkuItemVo;
import com.wjs.gulimall.gulimallproduct.VO.SpuItemAttrGroupVo;
import com.wjs.gulimall.gulimallproduct.entity.SkuImagesEntity;
import com.wjs.gulimall.gulimallproduct.entity.SpuInfoDescEntity;
import com.wjs.gulimall.gulimallproduct.feign.SecKillFeignService;
import com.wjs.gulimall.gulimallproduct.service.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.wjs.gulimall.gulimallproduct.dao.SkuInfoDao;
import com.wjs.gulimall.gulimallproduct.entity.SkuInfoEntity;


@Service("skuInfoService")
public class SkuInfoServiceImpl extends ServiceImpl<SkuInfoDao, SkuInfoEntity> implements SkuInfoService {
    @Autowired
    private SkuImagesService skuImagesService;

    @Autowired
    private SpuInfoDescService spuInfoDescService;

    @Autowired
    private AttrGroupService attrGroupService;

    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;

    @Autowired
    private SecKillFeignService secKillFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                new QueryWrapper<SkuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void saveSkuInfo(SkuInfoEntity skuInfoEntity) {
        this.save(skuInfoEntity);
    }

    @Override
    public PageUtils querySkuInfo(Map<String, Object> params) {
        QueryWrapper<SkuInfoEntity> wrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty((String) params.get("key"))) {
            wrapper.and((wq) -> {
                wq.eq("sku_id", key).or().like("sku_name", key);
            });
        }
        String brandId = (String) params.get("brandId");
        if (!StringUtils.isEmpty((String) params.get("brandId"))&&!"0".equalsIgnoreCase(brandId)) {
            wrapper.eq("brand_id", brandId);
        }
        String catelogId = (String) params.get("catelogId");
        if (!StringUtils.isEmpty((String) params.get("catelogId"))&&!"0".equalsIgnoreCase(catelogId)) {
            wrapper.eq("catalog_id", catelogId);
        }
        String min = (String) params.get("min");
        if (!StringUtils.isEmpty((String) params.get("min"))) {
            BigDecimal minx = new BigDecimal(min);
            if(minx.compareTo(new BigDecimal("0"))==1){
                wrapper.ge("price",min);
            }
        }
        String max = (String) params.get("max");
        if (!StringUtils.isEmpty((String) params.get("max"))) {
            BigDecimal maxs = new BigDecimal(max);
            if(maxs.compareTo(new BigDecimal(0))==1){
                wrapper.le("price",max);
            }

        }
        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Override
    public List<SkuInfoEntity> getSkuBySpuId(Long spuId) {
        List<SkuInfoEntity> spu_id = this.list(new QueryWrapper<SkuInfoEntity>().eq("spu_id", spuId));
        return spu_id;
    }

    @Override
    public SkuItemVo item(Long skuId) throws ExecutionException, InterruptedException {
        SkuItemVo skuItemVo=new SkuItemVo();
        // 1、sku基本获取 pms_sku_info
        CompletableFuture<SkuInfoEntity> infoFuture = CompletableFuture.supplyAsync(() -> {
            SkuInfoEntity skuInfo = getById(skuId);
            skuItemVo.setSkuInfo(skuInfo);
            return skuInfo;
        }, threadPoolExecutor);

        CompletableFuture<Void> saleFuture = infoFuture.thenAcceptAsync(r -> {
            // 3、获取spu的销售属性组合
            List<SkuItemSalAttrVo> salAttrVos = skuSaleAttrValueService.getSaleAttrsBySpuId(r.getSpuId());
            skuItemVo.setSaleAttr(salAttrVos);
        }, threadPoolExecutor);

        CompletableFuture<Void> descFuture = infoFuture.thenAcceptAsync(r -> {
            // 4、获取spu的介绍
            SpuInfoDescEntity desc = spuInfoDescService.getById(r.getSpuId());
            skuItemVo.setDesc(desc);
        }, threadPoolExecutor);

        CompletableFuture<Void> groupFuture = infoFuture.thenAcceptAsync(r -> {
            // 5、获取spu的规格参数信息
            List<SpuItemAttrGroupVo> attrGroupVos = attrGroupService.getgroupwithAttrsBySpuId(r.getSpuId(), r.getCatalogId());
            skuItemVo.setGroupAttrs(attrGroupVos);
        }, threadPoolExecutor);

        CompletableFuture<Void> imageFuture = CompletableFuture.runAsync(() -> {
            // 2、sku的图片信息 pms_sku_images
            List<SkuImagesEntity> images = skuImagesService.getImagesBySkuId(skuId);
            skuItemVo.setImages(images);
        }, threadPoolExecutor);

        CompletableFuture<Void> secKillFuture = CompletableFuture.runAsync(() -> {
            R r = secKillFeignService.getSkuSecKillInfo(skuId);
            if (r.getCode() == 0) {
                SecKillInfoVo killInfoVo = (SecKillInfoVo) r.getData(new TypeReference<SecKillInfoVo>() {
                });
                skuItemVo.setSecKillInfoVo(killInfoVo);
            }
        }, threadPoolExecutor);
        //等待所有任务完成
        CompletableFuture.allOf(saleFuture,descFuture,groupFuture,imageFuture,secKillFuture).get();
        return skuItemVo;
    }

}